package com.module.umlib.alipay;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.module.umlib.utils.Accept;
import com.module.umlib.utils.ConstantsUtils;

import java.util.Map;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

/**
 *
 */
public class AliPayFragment extends Fragment {

    private static String TAG = "AliPayFragment";
    private static BehaviorSubject<Accept> mObservable;

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDNCXVTdt/UGnozPe28uLBrLA5gFnQ3Rfp2jYM2+bxOV/kqa0F6YRNdPJVA7cDPSExYBsluOVa6nJPHWfWOpdj5pKhViet1Wg6nSHNKv31JE58grCs9HrZaUZPEblwvb4l2STQtfYcEGfW+1y+9nFDx7O2uiMasuniAPHdxItysNN9SqyadrDbh9Z2fbuALgkO0DFtV5r5x644O1dnpQE4aAcXt6R/6vF0pUj1PpR53IdAG8nXquCkFMoD+yDUCQcXEa7AcDWMHqG8enFHTzCXgSo1HB4otgUZ/OZ3p9sMelpbC8RaFEsi1fqL1ufvYZ3H68Vtqw6cK98jHDpdXg4iVAgMBAAECggEAM347nAGPxwn7RKE58pqDm/bNiW46M6N8eoehu43Or/JCHlgfcqesoE7VwR+0u5oRqk3SCr+Vu3oVVwy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xZ3xSpt1xZgn51FxC/WEjj62qQzzaJ/zs1GUYBrbWl6xdLeuTw=";

    private static final int SDK_PAY_FLAG = 1;


    public static AliPayFragment newInstance(FragmentActivity activity) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();

        AliPayFragment AliPayFragment = (AliPayFragment) fragmentManager.findFragmentByTag(TAG);
        boolean isNewInstance = AliPayFragment == null;
        if (isNewInstance) {
            AliPayFragment = new AliPayFragment();
            fragmentManager
                    .beginTransaction()
                    .add(AliPayFragment, TAG)
                    .commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }

        return AliPayFragment;
    }

    public IRxAliPay createObservable() {
        mObservable = BehaviorSubject.create();
        return new IRxAliPay() {

            @Override
            public Observable<Accept> aliPayment(String pAY_OrderInfo) {
                setAliPayOrderInfo(pAY_OrderInfo);
                return mObservable;
            }

        };
    }

    /**
     * 正式用于支付
     *
     * @param pAY_OrderInfo
     */
    public void setAliPayOrderInfo(final String pAY_OrderInfo) {
        //新开一个线程，将orderInfo字串传入到PayTask任务中去
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                //新建一个PAyTask对象
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(pAY_OrderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    Log.i("orderInfo", resultInfo.toString());
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        mObservable.onNext(new Accept(ConstantsUtils.Complete));
                        mObservable.onComplete();
                    } else {
                        mObservable.onNext(new Accept(ConstantsUtils.Failed));
                        mObservable.onComplete();
                        Toast.makeText(getContext(), payResult.getMemo(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }

        }

        ;
    };


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
